package com.xiaoq.coms.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class WeixinXmlUtil {
	public static <T> T fromByteArray(Class<T> clazz, byte[] licBytes) {
		try {
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Unmarshaller u = jc.createUnmarshaller();
			return (T) u.unmarshal(new ByteArrayInputStream(licBytes));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> T fromInputStream(Class<T> clazz, InputStream ins) {
		try {
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Unmarshaller u = jc.createUnmarshaller();
			return (T) u.unmarshal(ins);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> T fromString(Class<T> clazz, String str) {
		try {
			return fromByteArray(clazz, str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String asXml(Object obj) {
		try {
			JAXBContext jc = JAXBContext.newInstance(obj.getClass());
			Marshaller m = jc.createMarshaller();
			java.io.Writer writer = new java.io.StringWriter();
			m.marshal(obj, writer);
			return writer.toString().replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", "").replace("&lt;![CDATA[", "<![CDATA[").replace("]]&gt;", "]]>");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
